//
// Created by 王筱童 on 2022/5/9.
//

#include "others.h"

std::string nil="nil";
std::string ok="ok";

std::string serialize(const std::string &str) {
    std::uint64_t len = str.size();
    std::string head = transfer_to_byte(len);
    return head + str;
}
std::pair<std::string,std::string> deserialize(const std::string&bytes)
{
    constexpr std::size_t head_len = sizeof(std::uint64_t);
    std::string head = bytes.substr(0, head_len);
    std::uint64_t len = transfer_from_byte<std::uint64_t>(head);
    std::string res = bytes.substr(head_len, len);
    std::string tail = bytes.substr(head_len + len);
    return{ std::move(res),std::move(tail) };
}
std::pair<std::uint64_t, std::string> deserialize_head(const std::string&bytes)
{
    constexpr std::size_t head_len = sizeof(std::uint64_t);
    std::string head = bytes.substr(0, head_len);
    auto len = transfer_from_byte<std::uint64_t>(head);
    return { len,bytes.substr(head_len) };
}

std::vector<std::string> split(const std::string&str, char ch)
{
    int i = 0;
    std::vector<std::string> res;
    while (i < str.size()) {
        int now = 0;
        while (i + now < str.size() && str[i+now] != ch) {
            now++;
        }
        int ch_len=0;
        while (i+now+ch_len<str.size()&&str[i+now+ch_len]==ch)
        {
            ch_len++;
        }
        res.push_back(str.substr(i, now));
        i = i + now + ch_len;
    }
    return res;
}

std::string join(const std::vector<std::string>& vec, char ch)
{
    if (vec.empty()) {
        return "";
    }
    std::string res = vec[0];
    for (int i = 1; i < vec.size(); i++) {
        res += ch;
        res += vec[i];
    }
    return res;
}

std::string trim(const std::string& str)
{
    int i = 0;
    while (i < str.size() && str[i] == ' ')
        i++;
    return str.substr(i);
}

